package com.noahplat.fence.service.impl;

/**
 * 功能：围栏实现类
 * name:宋彦磊
 * time:2021.03.08
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.noahplat.alarm.feign.AlarmFeign;
import com.noahplat.alarm.pojo.Alarm;
import com.noahplat.common.cusexception.RedisException;
import com.noahplat.common.utils.NoahEnum;
import com.noahplat.common.utils.RedisUtils;
import com.noahplat.common.utils.Result;
import com.noahplat.common.utils.StatusCode;
import com.noahplat.fence.mapper.FenceMapper;
import com.noahplat.fence.mapper.FencereMapper;
import com.noahplat.fence.pojo.Fence;
import com.noahplat.fence.pojo.Fencere;
import com.noahplat.fence.service.FenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class FenceServiceImpl implements FenceService {

    @Autowired
    private FenceMapper fenceMapper;
    @Autowired
    private FencereMapper fencereMapper;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 增添围栏信息
     * 宋彦磊 2021.03.09
     * @param fence
     * @return
     */
    @Transactional
    @Override
    public Result addFence(Fence fence,String[] imei){
        fence.setCreattime(new Date());
        fence.setDel("N");
        fence.setApex("");
        int fenceres = fenceMapper.insert(fence);
        if(fenceres == 0){
            return new Result(false,StatusCode.ERROR,"添加围栏失败，请稍后再试");
        }

        if(!StringUtils.isEmpty(imei)){
            Set<String> set = new HashSet<>(Arrays.asList(imei));
            int fencereres = fencereMapper.insertFencere(set,fence.getId());
            if(fencereres == 0){
                return new Result(false,StatusCode.ERROR,"新增围栏关联关系失败，请稍后再试");
            }

            for(String key : set){
                boolean res = redisUtils.lSet(NoahEnum.FENCEDIR.getCode()+key,fence);
                if(!res){
                    throw new RedisException();
                }
            }
        }
        return new Result(true, StatusCode.OK,"添加围栏信息成功");
    }

    /**
     * 修改围栏信息
     * 宋彦磊 2021.03.09
     * @param fence
     * @return
     */
    @Transactional
    @Override
    public Result updateFence(Fence fence){
        int fenceres = fenceMapper.updateByPrimaryKeySelective(fence);
        if(fenceres == 0){
            return new Result(false,StatusCode.ERROR,"修改围栏信息出错，请稍后再试");
        }
        List<String> list = fencereMapper.getImei(fence.getId());
        if(!ObjectUtils.isEmpty(list)){
            for(String imei : list){
                boolean keyres = redisUtils.hasKey(NoahEnum.FENCEDIR.getCode()+imei);
                if(!keyres){
                    continue;
                }
                List<Object> list1 = redisUtils.lGet(NoahEnum.FENCEDIR.getCode()+imei,0,-1);
                if(ObjectUtils.isEmpty(list1)){
                    throw new RedisException();
                }
                for(Object object : list1){
                    Fence fence1 = (Fence) object;
                    if(fence.getId().equals(fence1.getId())){
                        list1.remove(object);
                        break;
                    }
                }
                boolean res =redisUtils.lSet(NoahEnum.FENCEDIR.getCode()+imei,fence);
                if(!res){
                    throw new RedisException();
                }
            }
        }
        return new Result(true,StatusCode.OK,"修改围栏信息成功");
    }

    /**
     * 修改围栏删除标识，代表已删除围栏
     * 宋彦磊 2021.03.09
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Result delFence(Long id){
        Fence fence = new Fence();
        fence.setDel("Y");
        Example example1 = new Example(Fence.class);
        example1.createCriteria().orEqualTo("id",id);
        int fenceres = fenceMapper.updateByExampleSelective(fence,example1);
        if(fenceres == 0){
            return new Result(false,StatusCode.ERROR,"删除围栏信息失败，请稍后再试");
        }

        List<String> list = fencereMapper.getImei(id);
        if(!ObjectUtils.isEmpty(list)){
            Example example = new Example(Fencere.class);
            example.createCriteria().orEqualTo("fid",id);
            int fencereres = fencereMapper.deleteByExample(example);
            if(fencereres == 0){
                return new Result(false,StatusCode.ERROR,"删除围栏关联关系失败，请稍后再试");
            }
            for(String imei : list){
                boolean keyres = redisUtils.hasKey(NoahEnum.FENCEDIR.getCode()+imei);
                if(!keyres){
                    continue;
                }
                List<Object> list1 = redisUtils.lGet(NoahEnum.FENCEDIR.getCode()+imei,0,-1);
                if(ObjectUtils.isEmpty(list1)){
                    throw new RedisException();
                }
                for(Object object : list1){
                    Fence fence1 = (Fence) object;
                    if(id.equals(fence1.getId())){
                        boolean keyres1 = redisUtils.hasKey(NoahEnum.FENCEDIR.getCode()+imei);
                        if(!keyres1){
                            continue;
                        }
                        long res = redisUtils.lRemove(NoahEnum.FENCEDIR.getCode()+imei,1,object);
                        if(res == 0){
                            throw new RedisException();
                        }
                        break;
                    }
                }
            }
        }

        return new Result(true,StatusCode.OK,"删除围栏信息成功");
    }

    /**
     * 查询未删除围栏信息
     * 宋彦磊 2021.03.09
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Result getFence(Integer page,Integer limit,Long uid,String imei){
        PageHelper.startPage(page, limit);
        List<Fence> list = null;
        if(StringUtils.isEmpty(imei)){
            Example example = new Example(Fence.class);
            example.createCriteria().andEqualTo("uid",uid).andEqualTo("del","N");
            list = fenceMapper.selectByExample(example);
            if(ObjectUtils.isEmpty(list)){
                return new Result(false,StatusCode.NOTFOUNDERROR,"暂无围栏数据");
            }
        }else {
            list = fenceMapper.getFence(imei,uid);
            if(ObjectUtils.isEmpty(list)){
                return new Result(false,StatusCode.NOTFOUNDERROR,"暂无围栏数据");
            }
        }

        PageInfo<Fence> pageInfo = new PageInfo<>(list);
        return new Result(true,StatusCode.OK,"查询围栏信息成功",pageInfo);
    }

    /**
     * 查询未删除围栏信息
     * 宋彦磊 2021.03.09
     * @return
     */
    @Override
    public Result getAppFence(Long uid,String imei){
        List<Fence> list = null;
        if(StringUtils.isEmpty(imei)){
            Example example = new Example(Fence.class);
            example.createCriteria().andEqualTo("uid",uid).andEqualTo("del","N");
            list = fenceMapper.selectByExample(example);
            if(ObjectUtils.isEmpty(list)){
                return new Result(false,StatusCode.NOTFOUNDERROR,"暂无围栏数据");
            }
        }else {
            list = fenceMapper.getFence(imei,uid);
            if(ObjectUtils.isEmpty(list)){
                return new Result(false,StatusCode.NOTFOUNDERROR,"暂无围栏数据");
            }
        }
        return new Result(true,StatusCode.OK,"查询围栏信息成功",list);
    }

    /**
     * 个人中心查询围栏
     * @return
     */
    @Override
    public Result getUidFence(Integer page, Integer limit,Long uid,String name){
        PageHelper.startPage(page, limit);
        Example example = new Example(Fence.class);
        example.createCriteria().andEqualTo("uid",uid).andEqualTo("del","N");
        if(!StringUtils.isEmpty(name)){
            example.and(example.createCriteria().andLike("name",name+"%"));
        }
        List<Fence> list = fenceMapper.selectByExample(example);
        if(ObjectUtils.isEmpty(list)){
            return new Result(false,StatusCode.NOTFOUNDERROR,"暂无围栏数据");
        }
        for(Fence fence : list){
            List<String> list1 = fencereMapper.getImei(fence.getId());
            fence.setImei(list1);
        }
        PageInfo<Fence> pageInfo = new PageInfo<>(list);
        return new Result(true,StatusCode.OK,"查询围栏信息成功",pageInfo);
    }


    /**
     * 根据ID查询围栏的详细信息
     * 宋彦磊 2021.03.09
     * @param id
     * @return
     */
    @Override
    public Result getFenceById(Long id){
        Example example = new Example(Fence.class);
        example.createCriteria().orEqualTo("id",id);
            Fence fence = fenceMapper.selectOneByExample(example);
        if(ObjectUtils.isEmpty(fence)){
            return new Result(false,StatusCode.ERROR,"查询出错，没查到对应数据");
        }
        List<String> list = fencereMapper.getImei(id);
        fence.setImei(list);
        return new Result(true,StatusCode.OK,"查询围栏信息成功",fence);
    }

    /**
     * 修改围栏关联关系
     * @param imei
     * @param newimei
     * @param fid
     * @return
     */
    @Transactional
    @Override
    public Result updateFencere(String[] imei,String[] newimei,Long fid){
        Example example1 = new Example(Fence.class);
        example1.createCriteria().orEqualTo("id",fid);
        Fence fence = fenceMapper.selectOneByExample(example1);
        if(ObjectUtils.isEmpty(fence)){
            return new Result(false,StatusCode.ERROR,"修改围栏关联关系失败，请稍后再试");
        }
        Set<String> setold = new HashSet<String>(Arrays.asList(imei));
        Set<String> nn = new HashSet<String>(Arrays.asList(newimei));
        setold.removeAll(nn);
        Set<String> old = new HashSet<String>(Arrays.asList(imei));
        Set<String> setnew = new HashSet<String>(Arrays.asList(newimei));
        setnew.removeAll(old);
        if(!ObjectUtils.isEmpty(setold)){
            Example example = new Example(Fencere.class);
            example.createCriteria().orEqualTo("fid",fid);
            example.and(example.createCriteria().andIn("imei",setold));
            int fencereres = fencereMapper.deleteByExample(example);
            if(fencereres == 0){
                return new Result(false,StatusCode.ERROR,"修改围栏关联关系失败，请稍后再试");
            }
            for(String oldimei : setold){
                boolean keyres = redisUtils.hasKey(NoahEnum.FENCEDIR.getCode()+oldimei);
                if(!keyres){
                    continue;
                }
                List<Object> list1 = redisUtils.lGet(NoahEnum.FENCEDIR.getCode()+oldimei,0,-1);
                if(ObjectUtils.isEmpty(list1)){
                    throw new RedisException();
                }
                for(Object object : list1){
                    Fence fence1 = (Fence) object;
                    if(fid.equals(fence1.getId())){
                        boolean keyres1 = redisUtils.hasKey(NoahEnum.FENCEDIR.getCode()+oldimei);
                        if(!keyres1){
                            continue;
                        }
                        long res = redisUtils.lRemove(NoahEnum.FENCEDIR.getCode()+oldimei,1,object);
                        if(res == 0){
                            throw new RedisException();
                        }
                        break;
                    }
                }
            }
        }

        if(!ObjectUtils.isEmpty(setnew)){
            int fencereres = fencereMapper.insertFencere(setnew,fid);
            if(fencereres == 0){
                return new Result(false,StatusCode.ERROR,"修改围栏关联关系失败,请稍后再试");
            }
            for(String nimei : setnew){
                boolean res = redisUtils.lSet(NoahEnum.FENCEDIR.getCode()+nimei,fence);
                if(!res){
                    throw new RedisException();
                }
            }
        }
        return new Result(true,StatusCode.OK,"修改围栏关联关系成功");
    }
}
